<template>
  <div id="mychart"></div>
</template>
<script>
export default {
  name: 'PieComponent',
  props: ['chartData', 'chartTitle', 'chartColor'],
  data () {
    return {
      mychart: null,
      title: '',
      color: ['#c23531', '#2f4554', '#61a0a8', '#d48265', '#91c7ae', '#749f83', '#ca8622', '#bda29a'],
      legend: ['直达', '营销广告', '搜索引擎', '邮件营销', '联盟广告', '视频广告', '百度', '谷歌', '必应', '其他', '邮件营销2', '联盟广告2', '视频广告2'],
      seriesData: []
    }
  },
  mounted () {
    let self = this;
    self.initChart(self.chartData);
    self.updateTitle(self.chartTitle);
    self.updateColor(self.chartColor);
    self.$on('updateData', self.initChart);
    self.$on('updateTitle', self.updateTitle);
    self.$on('updateColor', self.updateColor);
  },
  methods: {
    initChart (chartData) {
      let self = this
      self.legend = []
      self.seriesData = []
      self.mychart = self.$echarts.init(document.getElementById('mychart'))
      let xFieldData = Object.assign([], chartData.xFieldData)
      let yFieldData = Object.assign([], chartData.yFieldData)
      let yTitle = chartData.yTitle.map(function (item) { return { name: item.name, description: item.description } });
      for (let i = 0; i < xFieldData.length; i++) {
        self.legend.push(xFieldData[i]);
        self.seriesData.push({
          name: xFieldData[i],
          value: yFieldData[0][i]
        })
      }
      console.log(xFieldData);
      console.log(yFieldData);
      if (JSON.stringify(chartData) != '{}') {
        self.mychart.setOption({
          title: {
            text: self.title,
            x: 'center'
          },
          tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c} ({d}%)'
          },
          legend: {
            orient: 'vertical',
            left: 10,
            data: self.legend
          },
          color: self.color,
          series: [
            {
              name: yTitle[0].description == '' ? yTitle[0].name : yTitle[0].description,
              type: 'pie',
              selectedMode: 'single',
              radius: [0, '60%'],

              label: {
                // // position: 'inner',
                // show: false
              },
              labelLine: {
                show: false
              },
              data: self.seriesData
            }
          ]
        })
      }
    },
    updateTitle (value) {
      let self = this;
      self.title = value;
      console.log(value);
      self.mychart.setOption({
        title: {
          text: self.title
        }
      })
    },
    updateColor (value) {
      let self = this;
      console.log(value)
      self.color = value.map(function (item) { return item.value });
      self.mychart.setOption({
        color: self.color
      })
    }
  }
}
</script>
<style lang="stylus" scoped>
#mychart
  width 10rem
  height 4.8rem
</style>